<template>
  <div class="fruit-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchObj">
        <el-form-item label="水果名称">
          <el-input v-model="searchObj.fruit_name" placeholder="请输入名称" clearable />
        </el-form-item>
        <el-form-item label="产地">
          <el-input v-model="searchObj.origin" placeholder="请输入产地" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="handleAdd">
            <el-icon><Plus /></el-icon> 新增水果
          </el-button>
          <el-button type="primary" @click="loadData">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 水果列表（带图片） -->
    <div class="fruit-list">
      <el-card v-for="fruit in tableData" :key="fruit.fruit_id" class="fruit-card">
        <div class="fruit-img">
          <img
              :src="getFullImageUrl(fruit.img_url)"
              alt="水果图片"
              @error="() => (fruit.img_url = 'https://lys-java-bucket.oss-cn-beijing.aliyuncs.com/fruit/upload.png')"
          />
        </div>

        <div class="fruit-info">
          <h3 class="fruit-name">{{ fruit.fruit_name }}</h3>
          <div class="fruit-meta">
            <span>品种：{{ fruit.variety || '未知' }}</span>
            <span>产地：{{ fruit.origin || '未知' }}</span>
          </div>
          <div class="fruit-price">
            <span class="price">¥{{ Number(fruit.unit_price).toFixed(2) }}</span>
            <el-tag :type="fruit.is_availiable === 1 ? 'success' : 'danger'">
              {{ fruit.is_availiable === 1 ? '可售' : '下架' }}
            </el-tag>
          </div>
          <div class="fruit-actions">
            <el-button size="small" @click="handleEdit(fruit)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(fruit)">删除</el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 分页 -->
    <el-pagination
        class="pagination"
        v-model:current-page="searchObj.current"
        v-model:page-size="searchObj.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-sizes="[12, 24, 36]"
        @current-change="loadData"
        @size-change="handleSizeChange"
    />

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="isAdd ? '新增水果' : '编辑水果'" width="600px">
      <el-form :model="form" label-width="100px">
        <!-- 图片上传 -->
        <el-form-item label="水果图片" required>
          <el-upload
              class="uploader"
              :show-file-list="false"
              :http-request="handleUpload"
              :before-upload="beforeUpload"
          >
            <img v-if="form.imgUrl" :src="form.imgUrl" alt="预览" class="preview-img" />
            <img v-else src="https://lys-java-bucket.oss-cn-beijing.aliyuncs.com/fruit/upload.png" alt="预览" class="preview-img" />
          </el-upload>
        </el-form-item>

        <!-- 表单字段 -->
        <el-form-item label="水果名称" required>
          <el-input v-model="form.fruit_name" />
        </el-form-item>
        <el-form-item label="品种" required>
          <el-input v-model="form.variety" />
        </el-form-item>
        <el-form-item label="产地" required>
          <el-input v-model="form.origin" />
        </el-form-item>
        <el-form-item label="农户ID" required>
          <el-input v-model="form.farmer_id" />
        </el-form-item>
        <el-form-item label="单价(元)" required>
          <el-input v-model="form.unit_price" type="number" step="0.01" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.description" type="textarea" />
        </el-form-item>
        <el-form-item label="是否可售">
          <el-switch v-model="form.is_availiable" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { Plus } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import fruitApi from '@/api/fruit_api.js';
import { cloneDeep } from 'lodash';

// 列表与分页
const tableData = ref([]);
const total = ref(0);

// 搜索参数
const searchObj = ref({
  current: 1,
  limit: 12,
  fruit_name: '',
  origin: '',
});

// 弹窗与表单
const dialogVisible = ref(false);
const isAdd = ref(true);
const form = ref({
  fruit_id: '',
  fruit_name: '',
  variety: '',
  origin: '',
  farmer_id: '',
  unit_price: 0,
  description: '',
  imgUrl: '',          // 前端用于展示与收集的字段（驼峰）
  is_availiable: 1,
});

// 防缓存图片 URL
const getFullImageUrl = (imgUrl) => {
  if (!imgUrl) return imgUrl;
  const t = Date.now();
  return imgUrl.includes('?') ? `${imgUrl}&t=${t}` : `${imgUrl}?t=${t}`;
};

// 上传图片（新增不传 fruitId；编辑时传 fruitId，让后端可选地做绑定/清理）
const handleUpload = async (params) => {
  const formData = new FormData();
  formData.append('file', params.file);
  if (!isAdd.value && form.value.fruit_id) {
    formData.append('fruitId', String(form.value.fruit_id));
  }

  const token = localStorage.getItem('token');
  if (!token) {
    ElMessage.error('请先登录');
    return;
  }

  try {
    const res = await fruitApi.upload(formData, {
      headers: { Authorization: `Bearer ${token}` },
    });
    const imgUrl = (typeof res === 'string' && res) || res?.data || res?.url;
    if (!imgUrl) throw new Error('未拿到图片URL');
    form.value.imgUrl = imgUrl;
    params.onSuccess && params.onSuccess();
    ElMessage.success('图片上传成功');
  } catch (error) {
    params.onError && params.onError();
    ElMessage.error('图片上传失败: ' + (error?.response?.data?.message || error.message));
  }
};

// 文件上传前校验
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  const isSmallEnough = file.size / 1024 / 1024 < 2;
  if (!isImage) ElMessage.error('请上传图片文件');
  if (!isSmallEnough) ElMessage.error('图片大小不能超过 2MB');
  return isImage && isSmallEnough;
};

// 列表数据
const loadData = async () => {
  try {
    const res = await fruitApi.page(searchObj.value);
    tableData.value = res.data || [];
    total.value = res.count || 0;
  } catch (error) {
    ElMessage.error('加载失败');
  }
};

// 新增
const handleAdd = () => {
  isAdd.value = true;
  form.value = {
    fruit_id: '',
    fruit_name: '',
    variety: '',
    origin: '',
    farmer_id: '',
    unit_price: 0,
    description: '',
    imgUrl: '',
    is_availiable: 1,
  };
  dialogVisible.value = true;
};

// 编辑
const handleEdit = (fruit) => {
  isAdd.value = false;
  form.value = {
    ...cloneDeep(fruit),
    imgUrl: fruit.img_url || '',
  };
  dialogVisible.value = true;
};

// 删除
const handleDelete = async (fruit) => {
  try {
    await ElMessageBox.confirm(`确定删除【${fruit.fruit_name}】吗？`, '警告');
    await fruitApi.del(fruit.fruit_id);
    ElMessage.success('删除成功');
    loadData();
  } catch (error) {
    if (error?.message !== 'cancel') ElMessage.error('删除失败');
  }
};

// 提交（关键：把 imgUrl 映射成后端需要的 img_url）
const handleSubmit = async () => {
  try {
    if (!form.value.fruit_name) return ElMessage.warning('请输入水果名称');
    if (!form.value.imgUrl) return ElMessage.warning('请先上传图片');

    // 数值规整
    form.value.unit_price = Number(form.value.unit_price || 0);

    // 字段映射：前端 imgUrl -> 后端 img_url
    const payload = {
      ...form.value,
      img_url: form.value.imgUrl,
    };
    delete payload.imgUrl;

    if (isAdd.value) {
      await fruitApi.add(payload);
      ElMessage.success('新增成功');
    } else {
      await fruitApi.edit(payload);
      ElMessage.success('编辑成功');
    }
    dialogVisible.value = false;
    loadData(); //刷新数据
  } catch (error) {
    ElMessage.error(isAdd.value ? '新增失败' : '编辑失败');
  }
};

// 分页变化
const handleSizeChange = (val) => {
  searchObj.value.limit = val;
  searchObj.value.current = 1;
  loadData();
};

// 初始化与监听
onMounted(loadData);
watch(
    () => [searchObj.value.current, searchObj.value.limit],
    () => loadData()
);
</script>

<style scoped>
/* 基础布局 */
.fruit-container { padding: 20px; }
.search-card { margin-bottom: 20px; }

/* 卡片布局 */
.fruit-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}
.fruit-card { height: 100%; overflow: hidden; transition: transform 0.3s; }
.fruit-card:hover { transform: translateY(-5px); }

/* 图片样式 */
.fruit-img { width: 100%; height: 200px; background: #f5f5f5; overflow: hidden; }
.fruit-img img { width: 100%; height: 100%; object-fit: cover; }

/* 信息样式 */
.fruit-info { padding: 15px; }
.fruit-name { margin: 0 0 10px; font-size: 18px; color: #333; }
.fruit-meta { display: flex; gap: 15px; margin-bottom: 15px; color: #666; font-size: 14px; }
.fruit-price { display: flex; justify-content: space-between; align-items: center; margin: 10px 0; }
.price { font-size: 20px; color: #ff4d4f; font-weight: bold; }
.fruit-actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 10px; }

/* 分页 */
.pagination { text-align: center; margin-top: 20px; }

/* 图片预览 */
.preview-img { width: 100%; height: 200px; object-fit: cover; }
</style>
